package org.snail.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.util.TextUtils;

import java.util.*;

/**
 *  钉钉工具类
 */
public class CommonUtils {

    /**
     *  JSONObject 转换为Map
     * @param js
     * @return
     */
    public static HashMap<Long, Long> toHashMap(JSONObject js) {
        if (js == null) {
            return null;
        }
        HashMap<Long, Long> data = new HashMap<Long, Long>();
        // 将json字符串转换成jsonObject
        Set<String> set = js.keySet();
        // 遍历jsonObject数据，添加到Map对象
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = String.valueOf(it.next());
            Long keyLong = Long.valueOf(key);

            String value = js.getString(key);
            Long valueLong;
            if (TextUtils.isEmpty(value)) {
                valueLong = js.getLong(key);
            } else {
                valueLong = Long.valueOf(value);
            }
            data.put(keyLong, valueLong);
        }
        return data;
    }

    /**
     * 由于某些限制，需要导致list拆分成几个list
     * @param source  需要拆分的list
     * @param n     想分成几个List来做
     * @param <T>    list
     * @return     List<list>
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n){
        n = n==0?1:n;
        List<List<T>> result=new ArrayList<List<T>>();
        int remaider=source.size()%n;  //(先计算出余数)
        int number=source.size()/n;  //然后是商
        int offset=0;//偏移量
        for(int i=0;i<n;i++){
            List<T> value=null;
            if(remaider>0){
                value=source.subList(i*number+offset, (i+1)*number+offset+1);
                remaider--;
                offset++;
            }else{
                value=source.subList(i*number+offset, (i+1)*number+offset);
            }
            result.add(value);
        }
        return result;
    }


}
